package com.shenghua.controller;

import com.alibaba.fastjson.JSON;
import com.shenghua.dao.mapper.RoleLimitMapper;
import com.shenghua.dao.mapper.RolesMapper;
import com.shenghua.dao.model.*;
import com.shenghua.dao.page.Page;
import com.shenghua.service.RolesService;
import com.shenghua.utils.ListUtils;
import com.shenghua.utils.StringUtils;
import com.shenghua.utils.beans.Constants;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.MapUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/3/23.
 */
@Controller
@RequestMapping("/")
public class RolesController extends BaseController {
    Logger logger = LoggerFactory.getLogger(RolesController.class);
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private RoleLimitMapper roleLimitMapper;
    @Resource
    private RolesService rolesService;

    // 角色管理页面
    @RequestMapping(value = "/rolesManager/normal")
    public String rolesManagerPage_Normal() {
        return "pc/roles/rolesManager";
    }
    //分配权限页面
    @RequestMapping(value = "/allotLimits/normal/{id}")
    public String allotLimitsPage_Normal(Model model,
                                         @PathVariable(name = "id") Integer id) {
        model.addAttribute("id",id);
        return "pc/roles/allotRoles";
    }
    //新增角色页面
    @RequestMapping(value = "/addRoles/normal")
    public String addRolesPage_Normal() {
        return "pc/roles/addRoles";
    }
    //编辑角色页面
    @RequestMapping(value = "/editRoles/normal/{id}")
    public String editRolesPage_Normal(@PathVariable("id") String id,
                                       HttpServletRequest request, Model model) {
        Roles roles = rolesMapper.selectByPrimaryKey(Integer.parseInt(id));
        if(null == roles) {
            logger.error("[RolesController] editRolesPage_Normal 未找到指定角色");
            return "page500";
        }
        model.addAttribute("roles",roles);
        return "pc/roles/editRoles";
    }

    //查询权限信息
    @RequestMapping(value = "/selectRolesByPage/normal",method = RequestMethod.POST,
            produces = "application/json;charset=utf-8")
    @ResponseBody
    public String selectRolesByPage_Normal(@RequestParam Map<String,Object> params) {
        Dto<Map<String,Object>> dto = new Dto<>();
        Page page = getRequestPageInfo(params);
        dto = rolesService.queryRolesByPage(params, page);
        if(dto.isSuccess()) {
            logger.info("[RolesController] selectRolesByPage_Normal 查询权限信息成功！");
        } else {
            logger.error("[RolesController] selectRolesByPage_Normal 查询权限信息失败！");
        }
        return JSON.toJSONString(dto);
    }

    // 新增角色信息
    @RequestMapping(value = "/addNewRole/normal", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addNewLimit_Normal(Roles roles, HttpServletRequest request) {
        Dto<Roles> dto = new Dto<>();
        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[RolesController] addNewRole_Normal 用户未登录");
            dto.ReturnFail(new Roles(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if (null == roles) {
            logger.info("[RolesController] addNewRole_Normal 参数不能为空");
            dto.ReturnFail(new Roles(), ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        // 只允许一个超级管理员
        if(StringUtils.isNotBlank(roles.getSign()) &&
                Constants.ROLES_SUPER_ADMIN.equals(roles.getSign())) {
            RolesExample example = new RolesExample();
            RolesExample.Criteria criteria = example.createCriteria();
            criteria.andSignEqualTo(Constants.ROLES_SUPER_ADMIN);
            List<Roles> rolesList = rolesMapper.selectByExample(example);
            if(ListUtils.isNotEmpty(rolesList)) {
                logger.info("[RolesController] addNewRole_Normal 已经存在一个超级管理员：" + JSON.toJSONString(rolesList.get(0)));
                dto.ReturnFail(new Roles(), ErrorCode.ROLES_SUPER_ADMIN_ADD_FAIL);
                return JSON.toJSONString(dto);
            }
        }
        logger.info("[RolesController] addNewRole_Normal 新增角色信息：" + JSON.toJSONString(roles));
        roles.setCreated(new Date());
        roles.setCreateUserid(user.getId().toString());
        roles.setCreateNickname(user.getNickname());

        dto = rolesService.addNewRoles(roles);
        return JSON.toJSONString(dto);
    }

    // 编辑角色信息
    @RequestMapping(value = "/editCurrentRole/normal", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editCurrentRole_Normal(Roles roles, HttpServletRequest request) {
        Dto<Roles> dto = new Dto<>();
        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[RolesController] editCurrentRole_Normal 用户未登录");
            dto.ReturnFail(new Roles(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if (null == roles) {
            logger.info("[RolesController] editCurrentRole_Normal 参数不能为空");
            dto.ReturnFail(new Roles(), ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        // 只允许一个超级管理员角色
        if(StringUtils.isNotBlank(roles.getSign()) &&
                Constants.ROLES_SUPER_ADMIN.equals(roles.getSign())) {
            RolesExample example = new RolesExample();
            RolesExample.Criteria criteria = example.createCriteria();
            criteria.andSignEqualTo(Constants.ROLES_SUPER_ADMIN);
            List<Roles> rolesList = rolesMapper.selectByExample(example);
            if(ListUtils.isNotEmpty(rolesList)) {
                logger.info("[RolesController] addNewRole_Normal 已经存在一个超级管理员：" + JSON.toJSONString(rolesList.get(0)));
                dto.ReturnFail(new Roles(), ErrorCode.ROLES_SUPER_ADMIN_ADD_FAIL);
                return JSON.toJSONString(dto);
            }
        }
        logger.info("[RolesController] editCurrentRole_Normal 编辑角色信息：" + JSON.toJSONString(roles));
        roles.setUpdated(new Date());
        roles.setUpdateUserid(user.getId().toString());
        roles.setUpdateNickname(user.getNickname());

        dto = rolesService.editCurrentRoles(roles);
        return JSON.toJSONString(dto);
    }

    // 是否允许删除角色
    @RequestMapping(value = "/toDeleteRoles/normal/{id}")
    @ResponseBody
    public String toDeleteRoles_Normal(
            @PathVariable(name = "id") Integer id) {
        Dto<Roles> dto = new Dto<>();
        logger.info("[RolesController] toDeleteRoles_Normal 是否允许删除角色 id={}", id);
        RolesExample example = new RolesExample();
        RolesExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andSignEqualTo(Constants.ROLES_ADMIN);
        List<Roles> list = rolesMapper.selectByExample(example);
        if(ListUtils.isNotEmpty(list)) {
            logger.error("[RolesController] toDeleteRoles_Normal 权限属于管理员角色，不允许删除！");
            dto.ReturnFail(list.get(0), ErrorCode.ROLES_NOT_ALLOW_DELETE);
            return JSON.toJSONString(dto);
        }
        dto.ReturnSuccess(new Roles(), ErrorCode.ROLES_ALLOW_DELETE);
        return JSON.toJSONString(dto);
    }

    // 删除角色信息
    @RequestMapping(value = "/deleteRoles/normal/{id}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String deleteRoles_Normal(@PathVariable(name = "id") Integer id,
                                      HttpServletRequest request) {
        Dto<Roles> dto = new Dto<>();
        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[RolesController] deleteRoles_Normal 用户未登录");
            dto.ReturnFail(new Roles(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        RolesExample example = new RolesExample();
        RolesExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        List<Roles> list = rolesMapper.selectByExample(example);
        if(ListUtils.isEmpty(list)) {
            logger.error("[RolesController] deleteRoles_Normal 角色不存在，删除失败！");
            dto.ReturnFail(new Roles(), ErrorCode.ROLES_DELETE_FAIL);
            return JSON.toJSONString(dto);
        }
        Roles roles = list.get(0);
        if(Constants.ROLES_ADMIN.equals(roles.getSign()) ||
                Constants.ROLES_SUPER_ADMIN.equals(roles.getSign())) {
            logger.error("[RolesController] deleteRoles_Normal 角色属于管理员角色，不允许删除！");
            dto.ReturnFail(new Roles(), ErrorCode.ROLES_NOT_ALLOW_DELETE);
            return JSON.toJSONString(dto);
        }
        int i = rolesMapper.deleteByPrimaryKey(roles.getId());
        if(!(i>0)) {
            logger.error("[RolesController] deleteRoles_Normal 角色删除失败！");
            dto.ReturnFail(new Roles(), ErrorCode.ROLES_DELETE_FAIL);
            return JSON.toJSONString(dto);
        }
        logger.error("[RolesController] deleteRoles_Normal 角色删除成功！");
        dto.ReturnSuccess(roles, ErrorCode.ROLES_DELETE_SUCCESS);
        return JSON.toJSONString(dto);
    }

    // 保存角色权限信息
    @RequestMapping(value = "/saveRoles/normal/", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    //@Transactional(propagation = Propagation.REQUIRED)
    public String saveRoles_Normal(@RequestParam Map<String,Object> params,
                                   HttpServletRequest request) {
        Dto<RoleLimit> dto = new Dto<>();
        logger.info("[RolesController] saveRoles_Normal params={}", JSON.toJSONString(params));

        User user = (User) request.getSession().getAttribute("userSession");
        if (null == user) {
            logger.debug("[RolesController] saveRoles_Normal 用户未登录");
            dto.ReturnFail(new RoleLimit(), ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == params || MapUtils.isEmpty(params)) {
            logger.debug("[RolesController] saveRoles_Normal 参数为空");
            dto.ReturnFail(null, ErrorCode.ROLES_LIMIT_SAVE_FAIL);
            return JSON.toJSONString(dto);
        }
        String rolesId = params.get("rolesId").toString();
        logger.info("[RolesController] saveRoles_Normal rolesId={}", rolesId);
        String ids = params.get("ids").toString();
        logger.info("[RolesController] saveRoles_Normal ids={}", ids);
        if(StringUtils.isBlank(ids)) {
            logger.debug("[RolesController] saveRoles_Normal 参数为空");
            dto.ReturnFail(null, ErrorCode.ROLES_LIMIT_SAVE_FAIL);
            return JSON.toJSONString(dto);
        }
        String idd[] = ids.split(",");
        //@RequestParam("params[]") Integer[] params
        //List<Integer> list= Arrays.asList(params);
        RoleLimitExample example = new RoleLimitExample();
        RoleLimitExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(Integer.parseInt(rolesId));
        int i = roleLimitMapper.deleteByExample(example);
        boolean result = true;
        for (String id : idd) {
            RoleLimit rl = new RoleLimit();
            rl.setRoleId(Integer.parseInt(rolesId));
            rl.setLimitId(Integer.parseInt(id));
            rl.setCreated(new Date());
            rl.setCreateNickname(user.getNickname());
            rl.setCreateUserid(user.getId().toString());
            int j = roleLimitMapper.insert(rl);
            if(!(j>0)) {
                result = false;
                break;
            }
        }
        if(result) {
            dto.ReturnSuccess(new RoleLimit(), ErrorCode.ROLES_LIMIT_SAVE_SUCCESS);
        } else {
            dto.ReturnFail(null, ErrorCode.ROLES_LIMIT_SAVE_FAIL);
        }
        return JSON.toJSONString(dto);
    }

    //查询角色的权限信息
    @RequestMapping(value = "/selectRoleLimitByPage/normal",method = RequestMethod.POST,
            produces = "application/json;charset=utf-8")
    @ResponseBody
    public String selectRoleLimitByPage_Normal(@RequestParam Map<String,Object> params) {
        Dto<List<RoleLimit>> dto = new Dto<>();
        String rolesId = params.get("rolesId").toString();
        RoleLimitExample example = new RoleLimitExample();
        RoleLimitExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(Integer.parseInt(rolesId));
        List<RoleLimit> list = roleLimitMapper.selectByExample(example);
        if(ListUtils.isNotEmpty(list)) {
            logger.info("[RolesController] selectRoleLimitByPage_Normal 查询角色权限信息成功！");
            dto.ReturnSuccess(list, ErrorCode.ROLES_Query_SUCCESS);
        } else {
            logger.error("[RolesController] selectRoleLimitByPage_Normal 查询角色权限信息失败！");
            dto.ReturnSuccess(null, ErrorCode.ROLES_Query_FAIL);
        }
        return JSON.toJSONString(dto);
    }

    //查询权限Id和权限名称
    @RequestMapping(value = "/selectRolesForCombobox/normal",method = RequestMethod.POST,
            produces = "application/json;charset=utf-8")
    @ResponseBody
    public String selectRolesForCombobox_Normal(@RequestParam Map<String,Object> params) {
        String result = rolesService.queryRolesForCombobox();
        if(StringUtils.isNotBlank(result)) {
            logger.info("[RolesController] selectRolesForCombobox_Normal 查询权限信息成功！");
        } else {
            logger.error("[RolesController] selectRolesForCombobox_Normal 查询权限信息失败！");
        }
        return result;
    }

}
